package m202406.d25;

/**
 * @@author: 爱做梦的锤子
 * @date: 2024/6/26 15:02
 */
public class LCR073 {

    public static void main(String[] args) {
        LCR073 lcr073 = new LCR073();
        int i = lcr073.minEatingSpeed(new int[]{312884470}, 312884469);
        System.out.println(i);
    }

    public int minEatingSpeed(int[] piles, int h) {
        int max = Integer.MIN_VALUE;
        int min = 1;
        for (int pile : piles) {
            max = Math.max(pile, max);
        }

        max = max + 1;
        while (min < max) {
            int mid = (min + max) / 2;
            boolean canEat = canEat(mid, piles, h);
            if (!canEat) {
                min = mid + 1;
            } else {
                max = mid;
            }
        }
        return min;
    }

    private boolean canEat(int speed, int[] piles, int h) {
        int counter = 0;
        int i = 0;
        int current = 0;
        while (i < piles.length) {
            if (current == 0) {
                current = piles[i];
            }
            if (current <= speed) {
                i++;
                current = 0;
                counter++;
            } else {
                counter = counter + current / speed;
                current = current % speed;
                if (current == 0) {
                    i++;
                }
            }
            if (counter > h) {
                return false;
            }
        }
        return counter <= h;
    }
}
